package com.jiang.jixiang.ui;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.NearbyNearbyMerchantBean;
import com.jiang.jixiang.databinding.ActivitySellerlistBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.ui.adapter.NearbyMerchantAdapter;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.permission.SettingService;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 附近商家列表
 */
public class NearbySellerActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener, NetWorkListener {
    private ActivitySellerlistBinding binding;
    private NearbyMerchantAdapter nearbyMerchantAdapter;
    private NearbyNearbyMerchantBean nearbyNearbyMerchantBean;
    private int pageNumber = 1;
    private int pages;
    private SettingService mSettingService;
    private SearchView.SearchAutoComplete mSearchAutoComplete;
    private String searchKey;
    @Override
    protected void initCreate(Bundle savedInstanceState) {
        ManageActivity.putActivity(this.getClass().getSimpleName(), this);
        binding = ActivitySellerlistBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }

    @Override
    protected void initView() {
        binding.inTitle.titleTextTv.setText(R.string.title_nearby);
        binding.inTitle.titleLeftBtn.setOnClickListener(view -> {
            finish();
        });
        binding.refreshLayoutlive.setOnRefreshListener(this);//加载更多
        binding.refreshLayoutlive.setOnLoadMoreListener(this);//加载更多
        binding.refreshLayoutlive.autoRefresh();
        nearbyMerchantAdapter = new NearbyMerchantAdapter();

        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rcyData.setLayoutManager(manager);
        binding.rcyData.setAdapter(nearbyMerchantAdapter);


        binding.editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence newText, int i, int i1, int i2) {
                if (newText.equals("")) {
                    pageNumber = 1;
                    searchKey = "";
                    loadData();
                }else {
                    searchKey = String.valueOf(newText);
                    loadData();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        nearbyMerchantAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", nearbyMerchantAdapter.getData().get(position).getId());
                pageJump(NearbySellerInfoActivity.class, bundle);
            }
        });
    }

    private void loadData() {
        Map<String, Object> params = new HashMap<>();
        params.put("longitude", StringUtils.getString(getLocation().getLongitude()));
        params.put("latitude", StringUtils.getString(getLocation().getLatitude()));
        params.put("keyword",searchKey);
        params.put("type", "0");
        params.put("device_type", "powerbank");
        okHttpModel.postJson(ApiUrl.sellerList_Api, params, ApiUrl.sellerList_Api_ID, this);


    }

    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.sellerList_Api_ID:
                nearbyNearbyMerchantBean = GsonUtils.parseJObject(data.toString(), NearbyNearbyMerchantBean.class);
                if (nearbyNearbyMerchantBean != null) {
                    //pages = nearbyNearbyMerchantBean.getTotal();
                    pages = nearbyNearbyMerchantBean.getTotal() % page_size;
                    if (pages == 0) {
                        pages = nearbyNearbyMerchantBean.getTotal() / page_size;
                    } else {
                        pages = nearbyNearbyMerchantBean.getTotal() / page_size + 1;
                    }
                    if (pageNumber > 1) {
                        for (int i = 0; i < nearbyNearbyMerchantBean.getList().size(); i++) {
                            nearbyMerchantAdapter.getData().add(nearbyNearbyMerchantBean.getList().get(i));
                        }
                        nearbyMerchantAdapter.notifyDataSetChanged();
                    } else {
                        nearbyMerchantAdapter.setList(nearbyNearbyMerchantBean.getList());
                    }
                }
                break;
        }

    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());
    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.getMessage());
    }

    @Override
    protected void FinishDesTroy() {
        ManageActivity.removeActivity(this.getClass().getSimpleName());
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (refreshLayout != null) {
            pageNumber = 1;
            loadData();
            refreshLayout.finishRefresh();
            refreshLayout.resetNoMoreData();//setNoMoreData(false);//重置初始状态
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (refreshLayout != null) {
            if (pageNumber >= pages) {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            } else {
                pageNumber++;
                loadData();
                refreshLayout.finishLoadMore();
            }
        }
    }


}
